#!/usr/bin/python
# -*- coding: utf-8 -*-

import time, os, sys, urllib
from datetime import datetime
import simplejson as json
import logging

import tornado.ioloop
import tornado.web
import tornado.httpserver 
from modules.daemon import Daemon

from config import ABS_PATH, SOCKET_FUNCS_PATH, LOG_DIR, TORNADO_LOG_FILE, TORNADO_PORT

from webchatfuncs import get_last_messages, send_message_to_chat

logging.basicConfig(filename = TORNADO_LOG_FILE, level = logging.DEBUG)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world! %)")

class WebChatGetHandler(tornado.web.RequestHandler):
    def get(self):
        last_id = self.get_argument('last_id', None) or self.get_argument('from_id', None)
        format = self.get_argument('format', None)
        callback = self.get_argument('callback', None)
        messages, new_last_id = get_last_messages(last_id)
        if format == 'json':
            data = json.dumps({'data': messages, 'last_id': new_last_id})
            self.write(data)
        elif callback:
            self.set_header("Content-Type", "text/javascript")
            data = json.dumps({'data': messages, 'last_id': new_last_id})
            self.write("{callback}({data});".format(callback = callback, data = data));
        else:
            self.set_header("Content-Type", "text/javascript")
            data=json.dumps(messages);
            scriptText="data=%s; _lastId=%s; updateChatBox();"%(data, new_last_id)
            self.write(scriptText)
        return True

class WebChatPostHandler(tornado.web.RequestHandler):
    def get(self):
        self.process_request()
    def post(self):
        self.process_request()

    def process_request(self):
        callback = self.get_argument('callback', None)
        self.set_header("Content-Type", "text/javascript")
        nick, text = self.get_argument('nick'), self.get_argument('text')

        try: nick, text = urllib.unquote(nick), urllib.unquote(text)
        except: pass

        if nick and text:
            if not self.get_argument('simulate', False): send_message_to_chat(nick, text)
            logging.info("message sent! " + text)
            if callback:
                self.write("{callback}('success');".format(callback = callback) );
        else:
            logging.info("message not sent... nick: %s text: %s"%(nick, text))
            if callback:
                self.write("{callback}('error');".format(callback = callback) );

        return True


def log_request(handler):
    if handler.get_status() < 400:
        log_method = logging.info
    elif handler.get_status() < 500:
        log_method = logging.warning
    else:
        log_method = logging.error
    request_time = 1000.0 * handler.request.request_time()
    summary = handler._request_summary()
    if not 'GET /get?' in summary:
        log_method("%d %s %.2fms", handler.get_status(), summary, request_time)

class TornadoDaemon(Daemon):
    def run(self):
        server = tornado.web.Application([
            (r"/", MainHandler),
            (r"/js/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(ABS_PATH, 'js')}),
            (r"/css/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(ABS_PATH, 'css')}),
            (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(ABS_PATH, 'static')}),
            (r"/get", WebChatGetHandler),
            (r"/post", WebChatPostHandler),
            (r"/send", WebChatPostHandler),
        ], log_function = log_request)
        http_server = tornado.httpserver.HTTPServer(server) 
        http_server.listen(TORNADO_PORT) 
        tornado.ioloop.IOLoop.instance().start()
        sys.stdout.flush()
        sys.stderr.flush()
        time.sleep(10)

if __name__ == "__main__":
    stderr = os.path.join(LOG_DIR, 'tornado_err.log')
    daemon = TornadoDaemon('/tmp/webchat-daemon.pid', stdout = '/dev/null', stderr = stderr)
    if len(sys.argv) == 2:
        if 'run' == sys.argv[1]:
            daemon.run()
        elif 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)


